package com.gqj.meter.service.impl;

import com.gqj.common.constant.BusinessConstants;
import com.gqj.common.constant.UserConstants;
import com.gqj.common.core.domain.AjaxResult;
import com.gqj.common.enums.BusinessStatus;
import com.gqj.common.exception.ServiceException;
import com.gqj.common.utils.DateUtils;
import com.gqj.common.utils.StorageUtil;
import com.gqj.common.utils.StringUtils;
import com.gqj.meter.domain.*;
import com.gqj.meter.mapper.*;
import com.gqj.meter.service.IMdInTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 出入库任务Service业务层处理
 *
 * @author lxq
 * @date lxq-02-10
 */
@Service
public class MdInTaskServiceImpl implements IMdInTaskService {
    @Autowired
    private MdInTaskMapper mdInTaskMapper;
    @Autowired
    private MdInTaskDetailsMapper mdInTaskDetailsMapper;
    @Autowired
    private MdMeterMapper mdMeterMapper;
    @Autowired
    private MdItMapper mdItMapper;
    @Autowired
    private MdConcentratorMapper mdConcentratorMapper;

    /**
     * 查询出入库任务
     *
     * @param inTaskId 出入库任务主键
     * @return 出入库任务
     */
    @Override
    public MdInTask selectMdInTaskByInTaskId(Long inTaskId) {
        return mdInTaskMapper.selectMdInTaskByInTaskId(inTaskId);
    }

    /**
     * 查询出入库任务列表
     *
     * @param mdInTask 出入库任务
     * @return 出入库任务
     */
    @Override
    public List<MdInTask> selectMdInTaskList(MdInTask mdInTask) {
        return mdInTaskMapper.selectMdInTaskList(mdInTask);
    }

    /**
     * 新增出入库任务
     *
     * @param mdInTask 出入库任务
     * @return 结果
     */
    @Override
    public int insertMdInTask(MdInTask mdInTask) {
        return mdInTaskMapper.insertMdInTask(mdInTask);
    }

    /**
     * 修改出入库任务
     *
     * @param mdInTask 出入库任务
     * @return 结果
     */
    @Override
    public int updateMdInTask(MdInTask mdInTask) {
        Long inTaskId = mdInTask.getInTaskId();
        if (null == inTaskId) {
            throw new ServiceException("任务主键为null，请联系系统管理员！");
        }

        String statusCode = mdInTask.getStatusCode();
        if (null == statusCode || "".equals(statusCode)) {
            throw new ServiceException("任务状态代码为null，请联系系统管理员！");
        }
        MdInTask mdInTaskTemp = mdInTaskMapper.selectMdInTaskByInTaskId(inTaskId);

//        if (statusCode.equals("2") && !mdInTaskTemp.getStatusCode().equals("1")) {
//            throw new ServiceException("该任务不是执行中状态，无法完成！");
//        }
//
//        if (statusCode.equals("1") && !mdInTaskTemp.getStatusCode().equals("0")) {
//            throw new ServiceException("该任务不是待执行状态，无法执行！");
//        }

        //如果任务明细都执行完毕，则更改任务单状态
        MdInTaskDetails mdInTaskDetailQuery = new MdInTaskDetails();
        mdInTaskDetailQuery.setInTaskNo(mdInTaskTemp.getInTaskNo());

        if (statusCode.equals("2")) {
            mdInTask.setOperationDate(DateUtils.getNowDate());
            //修改子表完成
            List<MdInTaskDetails> mdInTaskDetailsList = mdInTaskDetailsMapper.selectMdInTaskDetailsList(new MdInTaskDetails() {{
                setInTaskNo(mdInTaskTemp.getInTaskNo());
            }});

            for (MdInTaskDetails mdInTaskDetails : mdInTaskDetailsList) {
                mdInTaskDetails.setOperationDate(DateUtils.getNowDate());
                mdInTaskDetails.setIsComplete(BusinessConstants.IS_COMPLETE);
                mdInTaskDetailsMapper.updateMdInTaskDetails(mdInTaskDetails);

                //根据设备码判断所属类型
                String assetsCategorySelect = StorageUtil.getEquipCodeType(mdInTaskDetails.getEquipCode());

                if (assetsCategorySelect.equals(BusinessConstants.ASSETS_CATEGORY_METER)) {
                    MdMeter mdMeter = new MdMeter();
                    mdMeter.setMeterId(mdInTaskDetails.getAssetsId());
                    mdMeter.setServiceStatus(BusinessConstants.SERVICE_STATUS_IN);
                    mdMeterMapper.updateMdMeter(mdMeter);
                } else if (assetsCategorySelect.equals(BusinessConstants.ASSETS_CATEGORY_CONCENTRATOR)) {
                    MdConcentrator mdConcentrator = new MdConcentrator();
                    mdConcentrator.setConcentratorId(mdInTaskDetails.getAssetsId());
                    mdConcentrator.setServiceStatus(BusinessConstants.SERVICE_STATUS_IN);
                    mdConcentratorMapper.updateMdConcentrator(mdConcentrator);
                } else if (assetsCategorySelect.equals(BusinessConstants.ASSETS_CATEGORY_IT)) {
                    MdIt mdIt = new MdIt();
                    mdIt.setItId(mdInTaskDetails.getAssetsId());
                    mdIt.setServiceStatus(BusinessConstants.SERVICE_STATUS_IN);
                    mdItMapper.updateMdIt(mdIt);
                }
            }
        }
        return mdInTaskMapper.updateMdInTask(mdInTask);
    }

    /**
     * 批量删除出入库任务
     *
     * @param inTaskIds 需要删除的出入库任务主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteMdInTaskByInTaskIds(Long[] inTaskIds) {
        for (Long inTaskId : inTaskIds) {
            MdInTask mdInTask = mdInTaskMapper.selectMdInTaskByInTaskId(inTaskId);
            mdInTaskDetailsMapper.deleteMdInTaskDetailsByInTaskNo(mdInTask.getInTaskNo());
        }
        return mdInTaskMapper.deleteMdInTaskByInTaskIds(inTaskIds);
    }

    /**
     * 删除出入库任务信息
     *
     * @param inTaskId 出入库任务主键
     * @return 结果
     */
    @Override
    public int deleteMdInTaskByInTaskId(Long inTaskId) {
        return mdInTaskMapper.deleteMdInTaskByInTaskId(inTaskId);
    }

    /**
     * 校验任务编号是否唯一
     *
     * @param mdInTask 任务信息
     * @return 结果
     */
    @Override
    public String checkInTaskNoUnique(MdInTask mdInTask) {
        Long inTaskId = StringUtils.isNull(mdInTask.getInTaskId()) ? -1L : mdInTask.getInTaskId();
        MdInTask info = mdInTaskMapper.checkInTaskNoUnique(mdInTask.getInTaskNo());
        if (StringUtils.isNotNull(info) && info.getInTaskId().longValue() != inTaskId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    //查询出入库统计信息
    @Override
    public Map<String, Object> getIoStatisticsInfo() {
        Map<String, Integer> inMap = mdInTaskMapper.getYearInNum();
        List<Integer> inNum = new ArrayList<>();
        for (String key : Arrays.asList("assets_category_01", "assets_category_02", "assets_category_04")) {
            inNum.add(inMap.getOrDefault(key, 0));
        }

        Map<String, Integer> outMap = mdInTaskMapper.getYearOutNum();
        List<Integer> outNum = new ArrayList<>();
        for (String key : Arrays.asList("assets_category_01", "assets_category_02", "assets_category_04")) {
            outNum.add(outMap.getOrDefault(key, 0));
        }

        Map<String, Object> ioStatisticsMap = new HashMap<>();
        ioStatisticsMap.put("inNum", inNum);
        ioStatisticsMap.put("outNum", outNum);
        return ioStatisticsMap;
    }

    /**
     * 新增出入库任务(工作台)
     *
     * @param mdInTask 出入库任务
     * @return 结果
     */
    @Override
    public int insertMdInTaskWorktop(MdInTask mdInTask) {
        //生成单号
        mdInTask.setInTaskNo("RK-" + StorageUtil.getOrderNoTo12());
        //任务状态默认完成
        mdInTask.setStatusCode(BusinessConstants.STATUS_CODE_END);
        //操作时间
        mdInTask.setOperationDate(DateUtils.getNowDate());
        //任务时间
        mdInTask.setTaskDate(DateUtils.getNowDate());
        //创建时间
        mdInTask.setCreateTime(DateUtils.getNowDate());
        int i = mdInTaskMapper.insertMdInTask(mdInTask);
        if (i > 0) {
            for (MdInTaskDetails mdInTaskDetails : mdInTask.getMdInTaskDetailsList()) {
                mdInTaskDetails.setInTaskNo(mdInTask.getInTaskNo());
                //是否完成
                mdInTaskDetails.setIsComplete(BusinessConstants.IS_COMPLETE_END);
                //使用设备
                mdInTaskDetails.setUseEquipment(BusinessConstants.USE_EQUIPMENT_WORKTOP);
                //完成时间
                mdInTaskDetails.setOperationDate(DateUtils.getNowDate());
                //查询物资详情插入详情表
                if (mdInTask.getAssetsCategory().equals(BusinessConstants.ASSETS_CATEGORY_METER)) {
                    //电能表
                    MdMeter meter = mdMeterMapper.selectMdMeterByRfidNo(mdInTaskDetails.getRfidNo());
                    if (meter == null) {
                        throw new ServiceException("电能表信息不存在，请检查后重试！");
                    }
                    mdInTaskDetails.setAssetsId(meter.getMeterId());
                    mdInTaskDetails.setRfidNo(meter.getRfidNo());
                    mdInTaskDetails.setMadeNo(meter.getMadeNo());
                    mdInTaskDetails.setSortCode(meter.getSortCode());
                    mdInTaskDetails.setTypeCode(meter.getTypeCode());
                    mdInTaskDetails.setEquipCode(meter.getEquipCode());
                    mdInTaskDetails.setEquipName(meter.getEquipName());

                    //修改电能表状态
                    mdMeterMapper.updateMdMeter(new MdMeter() {{
                        setMeterId(meter.getMeterId());
                        setServiceStatus(BusinessConstants.SERVICE_STATUS_IN);
                    }});
                } else if (mdInTask.getAssetsCategory().equals(BusinessConstants.ASSETS_CATEGORY_IT)) {
                    //互感器
                    MdIt it = mdItMapper.selectMdItByRfidNo(mdInTaskDetails.getRfidNo());
                    if (it == null) {
                        throw new ServiceException("互感器信息不存在请检查后重试");
                    }
                    mdInTaskDetails.setAssetsId(it.getItId());
                    mdInTaskDetails.setRfidNo(it.getRfidNo());
                    mdInTaskDetails.setMadeNo(it.getMadeNo());
                    mdInTaskDetails.setSortCode(it.getSortCode());
                    mdInTaskDetails.setTypeCode(it.getTypeCode());
                    mdInTaskDetails.setEquipCode(it.getEquipCode());
                    mdInTaskDetails.setEquipName(it.getEquipName());

                    //修改互感器状态
                    mdItMapper.updateMdIt(new MdIt() {{
                        setItId(it.getItId());
                        setServiceStatus(BusinessConstants.SERVICE_STATUS_IN);
                    }});
                } else if (mdInTask.getAssetsCategory().equals(BusinessConstants.ASSETS_CATEGORY_CONCENTRATOR)) {
                    //采集器
                    MdConcentrator concentrator = mdConcentratorMapper.selectMdConcentratorByRfidNo(mdInTaskDetails.getRfidNo());
                    if (concentrator == null) {
                        throw new ServiceException("采集器信息不存在请检查后重试");
                    }
                    mdInTaskDetails.setAssetsId(concentrator.getConcentratorId());
                    mdInTaskDetails.setRfidNo(concentrator.getRfidNo());
                    mdInTaskDetails.setMadeNo(concentrator.getMadeNo());
                    mdInTaskDetails.setTypeCode(concentrator.getTypeCode());
                    mdInTaskDetails.setEquipCode(concentrator.getEquipCode());
                    mdInTaskDetails.setEquipName(concentrator.getEquipName());

                    //修改采集器状态
                    mdConcentratorMapper.updateMdConcentrator(new MdConcentrator() {{
                        setConcentratorId(concentrator.getConcentratorId());
                        setServiceStatus(BusinessConstants.SERVICE_STATUS_IN);
                    }});
                }
                mdInTaskDetailsMapper.insertMdInTaskDetails(mdInTaskDetails);
            }
        }
        return i;
    }
}
